package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.DateConfig;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.AcademicWorkService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/academicWork")
public class AcademicWorkController {
    @Autowired
    private AcademicWorkService academicWorkService;
    @Autowired
    private UserService userService;

    /**
     * 管理员-查询学术著作列表
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/academicWorkList")
    public ResponseEntity<Map<String, Object>> academicWorkList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            System.out.println("前端："+params);
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<AcademicWork> page = new Page<>(currentPage, pageSize);
            QueryWrapper<AcademicWork> queryWrapper = new QueryWrapper<>();
//            System.out.println("paraams="+params);

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }

            //            // 模糊查询条件 - 项目名称
            if (params.containsKey("workName") && params.get("workName") != null && !params.get("workName").isEmpty()) {
                queryWrapper.like("work_name", params.get("workName"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("academicWorkCategory") && params.get("academicWorkCategory") != null && !params.get("academicWorkCategory").isEmpty()) {
                queryWrapper.like("academic_work_category", params.get("academicWorkCategory"));
            }

            // 模糊查询条件 - 项目类别
            if (params.containsKey("isbn") && params.get("isbn") != null && !params.get("isbn").isEmpty()) {
                queryWrapper.like("isbn", params.get("isbn"));
            }

            // 查询条件 - 出版时间
            if (params.containsKey("publishDate") && params.get("publishDate") != null && !params.get("publishDate").isEmpty()) {
                queryWrapper.apply("YEAR(publish_date) = {0}", params.get("publishDate"));
            }

            // 模糊查询条件 - 出版社名称
            if (params.containsKey("publisher") && params.get("publisher") != null && !params.get("publisher").isEmpty()) {
                queryWrapper.like("publisher", params.get("publisher"));
            }

            //状态
            if (params.containsKey("reviewStatus") && params.get("reviewStatus") != null && !params.get("reviewStatus").isEmpty()) {
                queryWrapper.eq("review_status", params.get("reviewStatus"));
            }

            // 查询条件 - 提交状态
            if (params.containsKey("academicStatus") && params.get("academicStatus") != null && !params.get("academicStatus").isEmpty()) {
                queryWrapper.eq("academic_status", params.get("academicStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<AcademicWork> resultPage = academicWorkService.getAWListWithUserInfo(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addAcademicWork")
    public ResponseEntity<Map<String, Object>> addAcademicWork(@RequestBody AcademicWork academicWork) {
        System.out.println("===" + academicWork);
        String username = academicWork.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

        // 4. 自动计算分值
        int baseScore = academicWorkService.getScoreByType(academicWork.getAcademicWorkCategory());
        academicWork.setAcademicWorkScore(baseScore);

        academicWork.setAcademicStatus("已提交");
        academicWork.setReviewStatus("未审核");
        academicWork.setSubmissionTime(LocalDateTime.now());





        // 判断该用户是否已经在 total_work 表中存在记录
//        QueryWrapper<AcademicWork> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        int count = academicWorkService.count(queryWrapper);
//
//        if (count > 0) {
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "该用户已存在，不能重复新增");
//            return ResponseEntity.badRequest().body(response);
//        }

        // 设置 userId 并保存
        academicWork.setUserId(userId);

        // 2. 计算总分值并保存到ScientificActivitySum表
        academicWorkService.calculateTotalScore(academicWork);
        academicWorkService.save(academicWork);

        //6、总分值
        String year = null;
        if (academicWork.getPublishDate() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(academicWork.getPublishDate());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = academicWork.getPublishDate().substring(0, 4);
            }
        }
        academicWorkService.updateTotalWorkAcademicScore(userId, year);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     * @param
     * @return
     */
    @DeleteMapping("/deleteAcademicWork")
    public ResponseEntity<Map<String, Object>> deleteAcademicWork(@RequestBody List<Long> academicWorkIds) {
        System.out.println("删除：" + academicWorkIds);
        // 1. 查询所有被删的记录
        List<AcademicWork> worksToDelete = academicWorkService.listByIds(academicWorkIds);

        // 2. 删除
        academicWorkService.removeByIds(academicWorkIds);

        // 3. 对每个 userId+year 组合，更新总分
        Set<String> userYearSet = new HashSet<>();
        for (AcademicWork work : worksToDelete) {
            if (work.getUserId() != null && work.getPublishDate() != null) {
                String year = null;
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(work.getPublishDate());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = work.getPublishDate().substring(0, 4);
                }
                String key = work.getUserId() + "_" + year;
                if (!userYearSet.contains(key)) {
                    academicWorkService.updateTotalWorkAcademicScore(work.getUserId(), year);
                    userYearSet.add(key);
                }
            }
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     * @param
     * @return
     */
    @PutMapping("/editAcademicWork")
    public ResponseEntity<Map<String, Object>> editAcademicWork(@RequestBody AcademicWork academicWork) {
//        System.out.println("::" + academicWork);

        // 1. 获取前端传递的用户名
        String username = academicWork.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            academicWork.setUserId(user.getUserId());
        }

        // 4. 自动计算分值
        int baseScore = academicWorkService.getScoreByType(academicWork.getAcademicWorkCategory());
        academicWork.setAcademicWorkScore(baseScore);
        // 2. 计算总分值并保存到ScientificActivitySum表
        academicWorkService.calculateTotalScore(academicWork);

        academicWorkService.updateById(academicWork);
        //6、总分值
        String year = null;
        if (academicWork.getPublishDate() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(academicWork.getPublishDate());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = academicWork.getPublishDate().substring(0, 4);
            }
        }
        academicWorkService.updateTotalWorkAcademicScore(academicWork.getUserId(), year);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 审核
     */
    @PostMapping("/reviewAcademicWork")
    public ResponseEntity<Map<String, Object>> reviewAcademicWork(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long academicWorkId = Long.valueOf(params.get("academicWorkId").toString());
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            AcademicWork academicWork = academicWorkService.getById(academicWorkId);
            if (academicWork == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            academicWork.setReviewStatus(reviewStatus);
            academicWork.setReviewTime(LocalDateTime.now());
            academicWork.setReviewResult(reviewResult);
            if ("审核通过".equals(reviewStatus)) {
                academicWork.setReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(reviewStatus)) {
                academicWork.setAcademicStatus("未提交");
            }
            // 同步 academicStatus 字段
//            if ("审核通过".equals(reviewStatus)) {
//                academicWork.setReviewStatus("审核通过");
//                academicWork.setReviewResult(null);
//            } else if ("审核不通过".equals(reviewStatus)) {
//                academicWork.setReviewStatus("审核不通过");
//                academicWork.setAcademicStatus("未提交");
//            }

            academicWorkService.updateById(academicWork);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportAcademicWorks(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {
        // 3. 查询 AcademicWork（可按年份筛选）
        QueryWrapper<AcademicWork> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("publish_date", year.substring(0, 4));
        }

        // 只导出审核通过的数据
        queryWrapper.eq("academic_status", "已提交");

        List<AcademicWork> list = academicWorkService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (AcademicWork w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "学术著作-" + now + ".xlsx";
//        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 7. 导出
        ExcelExportUtil.export(response, list, AcademicWork.class, "学术著作", fileName);
    }
}
